package ita.class1.group2.supermarket.administrator.filter;


import ita.class1.group2.supermarket.common.util.RespMessageFactory;
import ita.class1.group2.supermarket.common.auth.SecurityUtils;
import ita.class1.group2.supermarket.common.captain.CaptainApplication;
import ita.class1.group2.supermarket.common.util.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AdminFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        SecurityUtils securityUtils = (SecurityUtils) CaptainApplication.getInstance().getComponentManager().getBean(SecurityUtils.class);
        if(securityUtils.getSubject().isLogged()){
           chain.doFilter(request, response);
       }else{
            try {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest)request).getHeader("Origin"));
                httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
                ((HttpServletResponse)response).setContentType("application/json;charset=utf-8");
                ((HttpServletResponse)response).getWriter().write(JsonUtil.obj2json(RespMessageFactory.createSuccessMessage(false)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {

    }
}
